<template>
  <el-button v-bind="props" :icon="Search" @click="handleClick" v-show="props.show">{{props.label}}</el-button>
</template>

<script lang="ts" setup>
import eventBus from '@/event/eventBus';
import {onMounted, ref, onUnmounted, defineProps,inject,computed} from "vue";
import { Search } from '@element-plus/icons-vue';
import {replaceDynamicVar} from '@/api/tool/replacevar'
import {listInterfaceAll,convert2ApiJson,doRequest} from '@/api/business/interface'
import {
  queryParamKey,queryListResultKey,executeQueryKey,totalKey,loadingKey
} from "@/config/app.keys";
import { formModeKey } from '@/components/form/state.key';
import {ElButton, ElMessage} from 'element-plus'
interface Props {
  size?:string
  type?:string
  plain?:boolean
  text?:boolean
  bg?:boolean
  link?:boolean
  round?:boolean
  circle?:boolean
  loading?:boolean
  disabled?:boolean
  autofocus?:boolean
  formData?:object
  operationtype?:string
  operationdata:object,
  id?:string,
  label:string,
  show?:boolean,//是否显示
}

const props = withDefaults(defineProps<Props>(), {
  label: '搜索',
  show:true,
})
const formMode = inject(formModeKey)
const cMode = computed<FormFieldMode>(() => {
  if (props.mode) {
    return props.mode
  }
  if (formMode?.value) {
    return formMode.value
  }
  return "edit"
})
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
})
onMounted(() => {
  eventBus.$on(props.id+"_"+queryParamKey,(data) =>{
    console.log('queryParamKey:'+JSON.stringify(data.value));
    queryParams.value = data.value;
  })
  eventBus.$on(props.id+"_"+executeQueryKey,(data) => {
    console.log('SearchButton triggered, id:', JSON.stringify( data));
    queryParams.value = data;
    handleClick();
  })
})
onUnmounted(() =>{
  eventBus.$off(props.id+"_"+queryParamKey);
  eventBus.$off(props.id+"_"+executeQueryKey);
})



async function handleClick() {
  // 只有在 edit 模式下才执行删除操作
  if (cMode.value !== 'edit') {
    return;
  }
  //debugger;
  //替换变量值
  let opertionParameter = JSON.stringify(props.operationdata.parameterList);
  let contextMap = new Map();
  if(!props.formData){
    return;
  }
  console.log('props.formData:' + JSON.stringify(props.formData))
  let replaceParameters = replaceDynamicVar(props.formData, contextMap, opertionParameter)

  //将replaceParameters转换为json对象
  let jsonParameters = JSON.parse(replaceParameters);
  //调用API
    //改变装载状态
    eventBus.$emit(props.id+"_"+loadingKey,true);
    //根据接口编码查询接口信息
    let interfaceParam = {"interfaceCode": props.operationdata.interfaceCode};
    let interfaceInfo = await listInterfaceAll(interfaceParam);
    if (interfaceInfo.code === 200) {
      //调用接口
      let searchParameter =convert2ApiJson(jsonParameters)
      let apiParameter ={};
      apiParameter["interfaceCode"]=props.operationdata.interfaceCode
      //判断是否为翻页
      if(interfaceInfo.data[0].isPage=='Y'){
        apiParameter["pageNum"]=queryParams.value.pageNum;
        apiParameter["pageSize"]=queryParams.value.pageSize;
      }

      //判断接口为get,且不是通用接口时，则拼接到后面
      if(interfaceInfo.data[0].interfaceMethod=='GET'){
        apiParameter ={ ...apiParameter, ...searchParameter };
        //尝试替换url中的变量
        interfaceInfo.data[0].interfaceUrl = replaceDynamicVar(props.formData, contextMap, interfaceInfo.data[0].interfaceUrl);
      }else {
        //如果是通用,则单独一个searchConditon
        if(interfaceInfo.data[0].isCommonUrl=='Y'  ) {
          apiParameter["searchCondition"] = searchParameter;
        }else{
          //将searchParameter合并到apiParameter
          apiParameter ={ ...apiParameter, ...searchParameter };
        }
      }
      let res = await doRequest(interfaceInfo.data[0], apiParameter);

      if (res.code === 200) {
        //通知结果变化
        eventBus.$emit(props.id+"_"+queryListResultKey,res.rows);
        //applicationList.value = response.rows;
        //total.value = response.total;
        eventBus.$emit(props.id+"_"+totalKey,res.total)
        eventBus.$emit(props.id+"_"+loadingKey,false);
        ElMessage.success(res.msg)
      }else{
        ElMessage.error(res.msg || '操作失败！')
      }
    }

}


console.log('searchbutton $attrs:'+JSON.stringify(props));

</script>

<style scoped>

</style>
